package scalaExec.Interpreter;

import scalaExec.scalaLab.initScalaConsole;
import scalaExec.scalaLab.*;
import scalaExec.gui.*;

import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.*;
import scalalabEdit.*;
import scalaExec.ClassLoaders.ExtensionClassLoader;

import scalaExec.ClassLoaders.JarClassLoader;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import javax.script.SimpleBindings;
import javax.swing.table.DefaultTableModel;
import scala.tools.nsc.Settings;

public class GlobalValues
{
    // TODO:  matrix toolbar Matrix operations, i.e. A(':', 2, 2, 7)
    static public   String  scalalabBuildVersion = "7 - June - 11 ";
    
    static public boolean fastModeScripting = false;
    
    static public  boolean sameInterpreterForCells = true;
    static  public  scalaExec.scalaLab.initScalaConsole  initScalaConsoleObj;
    

    public static scala.tools.nsc.Interpreter  globalInterpreter;
    public static  scala.tools.nsc.Interpreter  cellsInterpreter;    // the Interpreter used to execute code in ScalaCodeCells
    
     public static  scala.collection.immutable.TreeMap<String, String>  bindedVarsTypes= null;
     public static DefaultTableModel model = new DefaultTableModel();
        
     public static   java.text.DecimalFormat availMemFormat = new java.text.DecimalFormat("0.00");
     public static JLabel availMemLabel;  // available memory model
     public static final int Inf = 9999999;   // a value denoting Inf at norm computations
     public static final int Fro = 6; // a value for the Frobenious norm
    // which Mat toolbox is used
    public static final int JAMAMat = 0;
    public static final int EJMLMat = 1;
    public static int toolboxUsed = JAMAMat;
    static public int libraryToUseForConsole = EJMLMat;
    
    
    public static boolean autoCompletionVariableSelected = false;  // avoid to execute text after selection of a variable from the autocompletion workspace
    public static boolean notOverlapTheConsoleOutput = true;  // avoid overlaping the Console with other windows
    public static double  mainFrameRelativeSize = 0.8;
    

    public  static JTextArea  lastResultOutputArea = new JTextArea();
        
    public static Runtime rt;  // the runtime for observing available memory
    public static long memAvailable;  // free memory available
   //ublic static 
    static public boolean autocompletionEnabled = false;   // controls loading automatically the autocompletion information
    static public Hashtable<String, String> scalaFunctionTypes = new Hashtable<String, String>();
    static public Map desktophints;
    static public boolean transparentErrorMessages = true;
    static public boolean verboseErrorMessages = false;
    static public FileTreeExplorer currentFileExplorer = null;
    // keep the variables participated at the ScalaSci binding. It is updated with scalaExec.gui.watchScalaWorkspace.displayScalaSciBinding()
    
    static public int bindingCnt = 0; // count of binded variables
    static public Vector bindedVarNames = new Vector();
    static public Vector bindedVarValues = new Vector();

   static public int  RGBAlpha, RGBRed, RGBBlue, RGBGreen;
   static public boolean displayScalaSciBindingGlobal = true;    // controls updating workspace list
   static public boolean displayCommandScalaSciBinding = true; // controls updating workspace list for the single command only
   // for retrieving Matlab .mat file variables
   static public double [][] data;
   static public double scalarData;
   
   static public Hashtable loadedClasses =  new Hashtable();  
   static  public int mxCharsToDisplayForValues  =  80;
   static public  JTabbedPane  scalaSciTabbedToolBar;

   static public JPanel  mainStatusPanel;
   static public  boolean useNewFigures = true;
   static public boolean withoutScalaLabLibs = true;    // do not import ScalaLabLibs
   static public boolean mainToolbarVisible = true;
   
     // Defaults for Main Help
    static public  String  JavaHelpSetName  = "jdk6Help";
    static public  String  BioJavaHelpSetName = "biojavaJH";
    static public  String  ScalaHelpSetName = "scalaHelp";
    static public  String  EJMLHelpSetName = "ejmlHelp";
    static public  String scalalabIDEHelpSetName = "IdeHelp";
    static public  String scalalabIntroHelpSetName= "scalalabIntro";
    static public  CSHObject  JavaCSHObject = null;
    static public  CSHObject  ScalaCSHObject = null;
    static public  CSHObject  BioJavaCSHObject = null;
    static public  CSHObject  EJMLCSHObject = null;
    
    static public  CSHObject  GettingStartedCSHObject = null;
    static public  CSHObject  scalalabIDEHelpObject = null;

    // the ExtensionClassLoader can be used to load at runtime classes contained in paths specified in ScalaSciClassPath
    static public ExtensionClassLoader extensionClassLoader = new ExtensionClassLoader("");
        
    static public String selectedExplorerPath;    // keeps the selected file system path with the ScalaLabExplorer
    static public String currentExpression;   // holds the text of the current expression in execution
        
    static public   int  doubleFormatLen = 4; // how many digits to display for doubles, Matrix
    static public   DecimalFormat fmtString = new  DecimalFormat("0.0000");
    static public   DecimalFormat fmtMatrix = new DecimalFormat("0.000"); // format Matrix results
        // these colors of the console input window  indicate the corresponding scalaLab operating modes
    static public  Color  ColorScalaSci = new Color(255, 255, 255);
    static public float alphaComposite = 0.5f;

         
        /**Constant with the application title.*/
    static public String TITLE="scalaLab - Scala/Java Scientific Laboratory  based on Scala "+scala.tools.nsc.Properties.versionString();
    static public long  timeForTic; // save the current time in milliseconds to implement tic-toc functionality
        
    static public boolean commandLineModeOn = true;  // execute line-by-line or accumulate buffer until F8?
    static public boolean scalaJarClassesLoaded = false;  // controls the loading/reloading of Scala classes
    static public boolean retrieveAlsoMethods = false; // retrieve also declared methods from toolboxes
    static public SimpleBindings scalaBindings = null;

    static public boolean truncateOutput  = false;   // displays all the output results from the Scala interpreter without truncating
    static public boolean globalVerboseOff = false;
    static public boolean displayAtOutputWindow = false;   // controls displaying at output window
    
    static public String currentToolboxName;   // keeps the currently loaded toolbox name
    
    
    static public    String  basicImportsJava =
                     "import java.awt.*; \n"+
                    "import java.awt.event.*; \n"+
                    "import javax.swing.*; \n"+   // Java standard UI and graphics support
                    "import javax.swing.event.*; \n"+
                    "import java.util.Vector; \n"+
                    "import numal.*; \n"+    // numerical analysis library routines
                    "import static numal.Linear_algebra.*;\n"+
                    "import scalaSci.math.plot.plot.*;\n"+     // plotting routines
                    "import static scalaSci.math.plot.plot.*; \n"+
                    "import scalaSci.math.io.MatIO.*; \n"+   // support for .mat Matlab files
                    "import java.text.DecimalFormat.*; \n"+
                    "import scalaSci.math.plot.*;\n"+
                    "import scalaSci.math.plot.effectsPlot.*;\n"+
                    "import scalaSci.math.plot.canvas.*; \n"+
                    "import scalaSci.math.plot.render.*; \n"+
                    "import scalaExec.Interpreter.GlobalValues; \n"+
                    "import java.lang.Math.*; \n"+
                    "import scalaSci.math.plot.*;\n";

               
         

    static public    String  basicImportsScala = 
                    "import _root_.java.awt._ ; \n"+
                    "import _root_.java.awt.event._ ; \n"+
                    "import _root_.javax.swing._ ; \n" +   // Java standard UI and graphics support
                    "import _root_.javax.swing.event._; \n"+
                    "import _root_.java.util.Vector ; \n"+
                
                    "import _root_.numal._ ; \n"+    // numerical analysis library routines
                    "import  _root_.numal.Linear_algebra._; \n"+
                    "import _root_.scalaSci.math.LinearAlgebra._\n"+
            
                    "import _root_.scalaSci.math.plot._;\n"+
                    "import _root_.scalaSci.math.plot.plot._;\n "+     // plotting routines
                     "import _root_.scalaExec.Interpreter.GlobalValues ; \n "+
                     "import _root_.scalaSci.Vec ; \n "+
                    "import _root_.scalaSci.Matrix ; \n"+
                    "import _root_.scalaSci.Mat ; \n"+ 
                     "import _root_.scalaSci.Vec._ ; \n "+
                     "import _root_.scalaSci.RichNumber; \n "+
                    "import _root_.scalaSci.Matrix._ ; \n"+
                    "import _root_.scalaSci.Mat._ ; \n"+ 
                     "import _root_.java.util.Random; \n"+
                    "import _root_.scalaSci.DoubleArr ; \n "+
                    "import _root_.scalaSci.DoubleDoubleArr ;\n "+
                    "import _root_.scalaSci.StaticMaths._ ; \n"+
                    "import  _root_.scalaSciCommands.BasicCommands \n  "+// + // support for ScalaSci's console commands
                 "import  _root_.scalaSciCommands.BasicCommands._; \n  "+// + // support for ScalaSci's console commands
               "import _root_.scalaSci.math.io.MatIO._ ; \n"+
                "import  _root_.jplot._;\n "+
                "import _root_.jplot.jFigure._;\n"+
                "import _root_.scalaSci.expIntOperator; \n"+
                "import _root_.scalaSci.expDoubleOperator; \n"+
                "import _root_.scalaSci.implicitConvOperators._; \n"+
               "import _root_.vplot._\n"+
                "import _root_.vplot.vfigure._\n"+
                 "import scalaSci.DD; \n"+
                 "import scalaSci.DD._; \n";
                    
                    
                   /* "import  no.uib.cipr.matrix._ \n"+
                    "import  no.uib.cipr.matrix.distributed._ \n"+
                    "import  no.uib.cipr.matrix.io._ \n"+
                    "import  no.uib.cipr.matrix.sparse._ \n"+
            */    
    
 //   static public String jplotsImports =                //"import jplot.jFigure._;\n"+               "import jplot.jplot; \n";
               
         
    static public String scalaPlusImports =          "import  _root_.scalaExec.Interpreter.GlobalValues.{Inf  =>Inf, Fro=>Fro} \n"+
                    "import _root_.scalaSci.DD._; \n"+
                    "import _root_.scalaSci.math.plot.render._ ; \n"+
                    "import _root_.scalaSci.math.plot.canvas._ ; \n"+
                    "import _root_.java.text.DecimalFormat._ ; \n"+
                     "import _root_.scala.collection.immutable.{List,BitSet, Stack,HashMap, Map,Set}; \n";
                  
    static public String scalaPlusEJMLImports =          "import  _root_.scalaExec.Interpreter.GlobalValues.{Inf  =>Inf, Fro=>Fro} \n"+
                      "import _root_.scalaSci.DD._; \n"+
                    "import _root_.scalaSci.math.plot.render._ ; \n"+
                    "import _root_.scalaSci.math.plot.canvas._ ; \n"+
                    "import _root_.java.text.DecimalFormat._ ; \n"+
                     "import _root_.scala.collection.immutable.{List,BitSet, Stack,HashMap, Map,Set}; \n"+
                      "import _root_.org.ejml.UtilEjml; \n"+
                    "import _root_.org.ejml.alg.dense.decomposition.DecompositionFactory; \n"+
                    "import _root_.org.ejml.alg.dense.decomposition.EigenDecomposition; \n"+
                    "import _root_.org.ejml.alg.dense.decomposition.SingularMatrixException; \n"+
                    "import _root_.org.ejml.alg.dense.decomposition.SingularValueDecomposition; \n"+
                    "import _root_.org.ejml.ops._; \n"+
                    "import _root_.org.ejml.simple.SimpleMatrix; \n"+
                    "import _root_.org.ejml.data.DenseMatrix64F; \n"+
                    "import _root_.scalaSci.EJML.Mat ; \n";
                    
                    
    
    static public    String  basicImportsEJMLScala = 
                    "import _root_.java.awt._ ; \n"+
                    "import _root_.java.awt.event._ ; \n"+
                    "import _root_.javax.swing._ ; \n" +   // Java standard UI and graphics support
                    "import _root_.javax.swing.event._; \n"+
                    "import _root_.java.util.Vector ; \n"+
                    "import _root_.numal._ ; \n"+    // numerical analysis library routines
                    "import  _root_.numal.Linear_algebra._; \n"+
                    "import _root_.scalaSci.math.LinearAlgebra._\n"+
                    "import _root_.scalaSci.Vec ; \n "+
                    "import _root_.scalaSci.Matrix ; \n"+
                    "import _root_.scalaSci.DoubleArr ; \n "+
                    "import _root_.scalaSci.DoubleDoubleArr ;\n "+
                     "import _root_.scalaExec.Interpreter.GlobalValues ; \n "+
                    "import _root_.scalaSci.math.plot._;\n"+
                    "import _root_.scalaSci.math.plot.plot._;\n "+     // plotting routines
                      "import _root_.scalaSci.math.io.MatIO._ ; \n"+   // support for .mat Matlab files
                   "import _root_.scalaSci.EJML.StaticMathsEJML._ ; \n"+
                    "import  _root_.scalaSciCommands.BasicCommands._; \n  "+
                    "import _root_.scalaSci.expIntOperator; \n"+
                "import _root_.scalaSci.expDoubleOperator; \n"+
                "import _root_.scalaSci.implicitConvOperators._; \n";
                    
     static public  String   implicitImportsScala =
                  "implicit def ArrayDoubleToVec(x: Array[Double]) =  scalaSci.StaticMaths.toVector(x) \n"+  // implicit conversion of an Array[Double] to Vector
                   "implicit def DoubleToRichNumber(x: Double) = new scalaSci.RichNumber(x) \n"+ 
                   "implicit def IntToRichNumber(x: Int) = new scalaSci.RichNumber(x) \n"+ 
                    "implicit def ShortToRichNumber(x: Short) = new scalaSci.RichNumber(x) \n"+       
                    "implicit def LongToRichNumber(x: Long) = new scalaSci.RichNumber(x) \n"+ 
                  "implicit def intToRational(x: Int) = new scalaSci.Rational(x) \n"+
                   "implicit def doubleArrToVec(x: Array[Double]) = new scalaSci.Vec(x) \n"+
                   "implicit def doubleDoubleArrToMat(x: Array[Array[Double]]) = new scalaSci.Mat(x) \n";


       static public Vector defaultImplicitsNames = new Vector();
  
        static public final int simpleTextFile = 0;  //  edit simple text file
        static public final int sigProcessingType = 1;  // Signal Processing ScalaSci project 
        static public final int javaClassFile = 2; // edit Java source file
        static public final int javaClassFileUsingScalalab =3;
        static public final int ScalaClassFile = 4;
        static public final int ScalaClassFileUsingScalalab = 5;
        static public final int scalaClass = 6;
        static public final int scalaClassSingletonObject = 7;
        static public final int scalaClassSingletonObjectWithCompanionClass = 8;
        static public final int scalaClassFileUsingScalalab = 9;
        static public final int javaExternalClassFileUsingScalalab =10;
        static public final int scalaClassFileUsingScalalabBioJava = 11;
        static public final int javaClassFileUsingScalalabBioJava = 12;


        static public int varLenToDisplay = 20; // controls how much of a large variable (e.g. a large matrix) to display 
        
        static public ImageIcon  scriptingModeConfigIcon;
        static public Image  scalaImage;
        static public Image  smallScalaImage;
        
        static public java.text.DecimalFormat  scalalabNumberFormat = new java.text.DecimalFormat("0.000");
	
        static public int numericComputeThreadCnt = 4;  // number of threads to create for parallel operationss
        static public char parallelOperator = '&';  // triggers parallel execution 
        
        static public String  smallNameFullPackageSeparator = "-->";  // separates small Java  method/class names from their full package specifiers for getting help with only the small name
        
           // Console Configuration
        static String defaultFontName = "Arial";
        static String  defaultFontSize = "14";
        static public Font   defaultTextFont; 
        static String defaultConsoleFontName = "Lucida";
        static String  defaultConsoleFontSize = "14";

        static public String detailHelpStringSelected="";
        static public boolean  extensionClassPreload = true;  // preload extension classes into internal
                                                                            // cache to avoid loading them later on demand
        static public boolean loadAlwaysClassesFromSystemPath = true;   // load classes from system path even if preloaded enabled
        static public boolean  loadJarClasses = true;  // load classes from .jar archive
	static public boolean hostIsUnix;   // Unix like system or Windows?
        
        static public String jarFilePath="";  // the path that contains the main jar file
        static public String fullJarFilePath="";
        static public String scalalabLibPath="";
        
        
        
  // ScalaSciClassPath is the directory that serves as the "root" for Scala Class Loader class retrieval. 
 // This directory and all its subdirectories are searched for both .Scala script files and .class files        
        static public String ScalaSciClassPath=""; 
        static public Vector ScalaSciClassPathComponents=new Vector();
        
    // these variables keep the user preferable toolboxes that can be saved during a working session.
   // these toolboxes can then be automatically reloaded
        static public Vector  ScalaSciToolboxes = new Vector();
        static public Vector  ScalaSciUserPaths = new Vector();
        
        static public Vector  favouriteElements = new Vector();


        
        static public String scalalabPropertiesFile;  // the file for obntaining configuration properties
        static public String workingDir;  // the current working directory
        static public String homeDir;  // the user's home directory
        
        static public HashMap<String, Boolean>  jartoolboxesLoadedFlag;  // associates each jar toolbox name with a flag that indicates whether it was loaded or not
        ////static public JarClassLoader ScalaToolboxesLoader;  // the loader that handles the classes supplied with toolboxes
        
        static public int sizeX = 600;  // the scalaLab's main console window jFrame size
        static public int sizeY = 400;  
        static public int locX = 100;   // location of scalaLab's main window
        static public int locY = 100; 
        
        static public int sizeConsoleX = 600;  // the scalaLab's output console window jFrame size
	static public int sizeConsoleY = 100;  
        static public int locConsoleX = 100;   // location of scalaLab's main window
        static public int locConsoleY = 800; 
        
        static public double figAreaRelSize = 0.9;  // the relative area of the figure plot area
        
    static public int threadCnt = 0;  // the number of threads created

    static public int maxNumberOfRecentFiles = 20;
    static public String scalaLabRecentFilesList = "scalaLabRecentFiles.txt";   // the file for storing list of recent files
    
    static public boolean displayDirectory = true; // controls the displaying of working directory at the prompt
    static public char scalalabPromptChar = '#';  // used to display the command prompt
    static public String scalalabPromptString = scalalabPromptChar+" ";
    static public String scalaCommandPromptString =  "scala >";
    
    static public JarClassLoader ScalaToolboxesLoader = null;
    
    public static TreeSet [] loadedClassesOfToolboxes;  // keeps track of loaded classes from all toolboxes
    public static String [] loadedToolboxesNames;  // the names of the toolboxes
    public static int currentToolboxId = 0; 
    public static int maxNumOfToolboxes = 30;

    
      
    
    // Graphics Configuration
    public static int  maxPointsToPlot = 40;  // limit on the number of points to plot when in point plot mode
    public static int  plotPointWidth = 2;    // control the size of the point at the plots 
    public static int  plotPointHeight =2; 
    public static int  markLineSize = 5;
    public static int  figGridSizeX = 30; 
    public static int  figGridSizeY = 30;     
    public static int  figFrameSizeX = 800; 
    public static int  figFrameSizeY = 600;     
    public static int  limitForLargeRangeOfValues = 10;
    public static double figZoomScaleFactor = 0.5;
    public static int currentMaxNumberOfZooms = 5;

         // the tabs of the main UI 
    public static final int mainTab = 0;
    public static final int javaHelpTab = 1;
    public static final int scalaHelpTab = 2;
    public static final int scalaSciTab = 3;

    public static Dimension ScreenDim;

    static public String  scalalabCommandHistoryFile = "scalalabCommandHistory.log";
    static public String scalalabFavoritePathsFile = "scalalabFavoritePaths.log";
    static public int  numOfHistoryCommandsToKeep  = 10;  // size of the command history list 

    static public String DirHavingFile;  // directory having the currently requested file
    static public Properties settings;  // for load/save global properties
    static public String selectedStringForAutoCompletion;
    
    public static AutoCompletionScalaSci  autoCompletionScalaSci;    // structures for supporting autocompletion for ScalaSci
    public static AutoCompletionScalaSciLoader  autoCompletionScalaSciLoader;  // loader of ScalaSci classes for autocompletion
    
    public static AutoCompletionWorkspace autoCompletionWorkspace = new AutoCompletionWorkspace();
    
    public static int numTokTypes = 0;   // counts the number of token types that the lexical analyzer returns
      
    // keep main objects
    public static scalaLab   scalalabMainFrame = null;
    public static int xSizeTab;
    public static int ySizeTab;
    public static AutoCompletionFrame autoCompletionFrame = null;
    public static  scalalabEditor  myEdit = null;
    public static scalaExec.gui.Console  userConsole;         //  used to retrieve the text buffer
    
    public static boolean effectsEnabled=false;
    
    public static SysUtils.ConsoleWindow  consoleOutputWindow;
    public static int lastIndexOfOutput=0;
    public static String assemblyFileName;
    public static String pascalWorkingDir;
       
    public static void initGlobals()
    {
        lastResultOutputArea.setToolTipText("The result of the last command");
        Toolkit tk =Toolkit.getDefaultToolkit();
        desktophints = (Map)(tk.getDesktopProperty("awt.font.desktophints"));

        GlobalValues.fmtMatrix.setDecimalFormatSymbols(new DecimalFormatSymbols(new Locale("us")));
        GlobalValues.fmtString.setDecimalFormatSymbols(new DecimalFormatSymbols(new Locale("us")));

        GlobalValues.workingDir = System.getProperty("user.dir");
        java.util.Map<String, String>  userEnv = System.getenv();

        GlobalValues.homeDir = userEnv.get("HOMEPATH");
          if (GlobalValues.homeDir == null)
              GlobalValues.homeDir = GlobalValues.workingDir; // perhaps old versions of Windows do not have a home path
        
        if (GlobalValues.workingDir.indexOf("Windows")!=-1)  // avoid using Windows system directory
            GlobalValues.workingDir = GlobalValues.homeDir;

        GlobalValues.DirHavingFile = GlobalValues.workingDir;
        ScalaSciClassPathComponents = new Vector();
        
        GlobalValues.ScalaSciUserPaths.add(GlobalValues.homeDir);
        
        ScalaSciToolboxes = new Vector();
        
        hostIsUnix = true;
        if (File.separatorChar!='/') 
            hostIsUnix=false;

        myEdit = null;
        loadedClassesOfToolboxes = new TreeSet[maxNumOfToolboxes];
        loadedToolboxesNames = new String[maxNumOfToolboxes];
        
        jartoolboxesLoadedFlag = new HashMap<String, Boolean>();

        String  prefix = "/";
        if (hostIsUnix==false)
            prefix = "C:\\";

        String initialScalalabPath  =prefix;
        
        boolean foundConfigFileFlag = false;   //exists configuration file?
     try
        {  
           settings = new Properties();
       
           FileInputStream in = null;
           
           String configFileName = workingDir+File.separatorChar+"scalalab.props";
           File configFile = new File(configFileName);
           if (configFile.exists())   {
                  in = new FileInputStream(configFile);
                  settings.load(in);
                  foundConfigFileFlag = true;
                  GlobalValues.scalalabPropertiesFile = configFileName;
                  }
    defaultImplicitsNames.add("ArrayDoubleToVec"); defaultImplicitsNames.add("DoubleToVec"); defaultImplicitsNames.add("IntToVec");
    defaultImplicitsNames.add("ShortToVec"); defaultImplicitsNames.add("LongToVec"); defaultImplicitsNames.add("DoubleToMat");
    defaultImplicitsNames.add("IntToMat");  defaultImplicitsNames.add("ShortToMat"); defaultImplicitsNames.add("LongToMat");
    defaultImplicitsNames.add("DoubleToMatrix"); defaultImplicitsNames.add("IntToMatrix"); defaultImplicitsNames.add("ShortToMatrix");
    defaultImplicitsNames.add("LongToMatrix"); defaultImplicitsNames.add("intToRational"); defaultImplicitsNames.add("doubleArrToVec");
    defaultImplicitsNames.add("doubleDoubleArrToMat"); defaultImplicitsNames.add("vecToMat");  defaultImplicitsNames.add("vecToMatrix");
    defaultImplicitsNames.add("vecToEJMLMat");
           }

        catch (IOException e) 
        {
           e.printStackTrace();
        }
         ScreenDim = Toolkit.getDefaultToolkit().getScreenSize();

         settings.put("ScalaSciClassPathProp", initialScalalabPath);
        
        if (foundConfigFileFlag == false)   { // configuration file not exists, thus pass default configuration
                //position the frame in the centre of the screen
                int xSizeMainFrame = (int)((double)ScreenDim.width/1.4);
                int ySizeMainFrame = (int)((double)ScreenDim.height/1.4);
                GlobalValues.locX  = (int)((double)ScreenDim.width/10.0);  
                GlobalValues.locY = (int)((double)ScreenDim.height/10.0); 
               
                GlobalValues.sizeX = xSizeMainFrame;
                GlobalValues.sizeY = ySizeMainFrame;
                
                
        // pass default properties
        settings.put("widthProp",  String.valueOf(xSizeMainFrame));
        settings.put("heightProp", String.valueOf(ySizeMainFrame));
        settings.put("xlocProp",  String.valueOf(GlobalValues.locX));
        settings.put("ylocProp",  String.valueOf(GlobalValues.locY));

        // append homedir to the initial scalaSci classpath
        String userDir = workingDir;


        settings.put("ScalaSciToolboxesProp", "");   // the property that keeps the user toolboxes
        settings.put("ScalaSciUserPathsProp", "");   // the property that keeps the user specified paths
        
        settings.put("scalalabWorkingDirProp", userDir);
        
        settings.setProperty("uiFontNameProp","Arial");
        settings.setProperty("uiFontSizeProp", "16");
        settings.setProperty("consoleFontNameProp", "Lucida");
        settings.setProperty("consoleFontSizeProp", "14");
        
        settings.setProperty("loadScalaSciAutoCompletionProp", "true");
        } // configuration file not exists
            
           
        defaultTextFont = new Font(settings.getProperty("uiFontNameProp"), Font.PLAIN, 14);     

    }   

    
    
    public static void incrementToolboxCount() {
        currentToolboxId++;
        if (currentToolboxId > maxNumOfToolboxes)  { 
            JOptionPane.showMessageDialog(null, "Maximum toolbox count exceeded", "Cannot load additional toolboxes", JOptionPane.ERROR_MESSAGE);
        }
    }
    
// pass properties readed from settings Property String to the scalaLab workspace structures
    public static void passPropertiesFromSettingsToWorkspace(Properties settings)
     {
        
        String specifiedDir =  settings.getProperty("scalalabWorkingDirProp");         
        if (specifiedDir != null) workingDir = specifiedDir;
        
       String locXstr = settings.getProperty("xlocProp");
        if (locXstr != null)      locX = Integer.parseInt(locXstr);  // locX specified
        String locYstr = settings.getProperty("ylocProp");
        if (locYstr != null)      locY = Integer.parseInt(locYstr);  // locY specified
        if (GlobalValues.scalalabMainFrame != null)
            GlobalValues.scalalabMainFrame.setLocation(locX, locY);   // update the location of the scalalab's main frame according to the configuration settings

        String sizeXstr = settings.getProperty("widthProp");
        if (sizeXstr != null)      sizeX = Integer.parseInt(sizeXstr);  // sizeX specified
        String sizeYstr = settings.getProperty("heightProp");
        if (sizeYstr != null)      sizeY = Integer.parseInt(sizeYstr);  // sizeY specified
        if (GlobalValues.scalalabMainFrame != null)
            GlobalValues.scalalabMainFrame.setSize(sizeX, sizeY);   // update the size of the scalalab's main frame according to the configuration settings
        
        
       String sizeConsoleXstr = settings.getProperty("widthConsoleProp");
        if (sizeConsoleXstr != null)      sizeConsoleX = Integer.parseInt(sizeConsoleXstr);  // sizeX Console specified
        String sizeConsoleYstr = settings.getProperty("heightConsoleProp");
        if (sizeConsoleYstr != null)      sizeConsoleY = Integer.parseInt(sizeConsoleYstr);  // sizeY Console specified
        if (GlobalValues.scalalabMainFrame.scalalabConsole != null)
            GlobalValues.consoleOutputWindow.consoleFrame.setSize(sizeConsoleX, sizeConsoleY);   // update the size of the output Console's frame according to the configuration settings

        String locConsoleXstr = settings.getProperty("xlocConsoleProp");
        if (locConsoleXstr != null)      locConsoleX = Integer.parseInt(locConsoleXstr);  // locX Console specified
        String locConsoleYstr = settings.getProperty("ylocConsoleProp");
        if (locConsoleYstr != null)      locConsoleY = Integer.parseInt(locConsoleYstr);  // sizeY Console specified
        if (GlobalValues.scalalabMainFrame.scalalabConsole != null)
            GlobalValues.consoleOutputWindow.consoleFrame.setLocation(locConsoleX, locConsoleY);   // update the size of the output Console's frame according to the configuration settings
        
        
        
        String uiFontName = settings.getProperty("uiFontNameProp");
        if (uiFontName==null) uiFontName= GlobalValues.defaultFontName;
        String uiFontSize = settings.getProperty("uiFontSizeProp");
        if (uiFontSize==null) uiFontSize= GlobalValues.defaultFontSize;
        
        String consoleFontName = settings.getProperty("consoleFontNameProp");
        if (consoleFontName==null) consoleFontName= GlobalValues.defaultConsoleFontName;
        String consoleFontSize = settings.getProperty("consoleFontSizeProp");
        if (consoleFontSize==null) consoleFontSize= GlobalValues.defaultConsoleFontSize;
        if (GlobalValues.scalalabMainFrame != null)
          GlobalValues.scalalabMainFrame.scalalabConsole.setFont(new Font(consoleFontName, Font.PLAIN, Integer.parseInt(consoleFontSize)));
            
        /*
        String ScalaSciToolboxesStr = settings.getProperty("ScalaSciToolboxesProp");   // the ScalaSci toolboxes as .jar files
        if (ScalaSciToolboxesStr != null) {
        StringTokenizer  toolboxesTok = new StringTokenizer(ScalaSciToolboxesStr, File.pathSeparator);
        while (toolboxesTok.hasMoreTokens())  {
            String  forScalaToolboxJarName = toolboxesTok.nextToken();  // full path name of the toolbox JAR file
            scalaSciCommands.BasicCommands.appendClasspath(forScalaToolboxJarName);    // append the Scala's interpreter classpath to account for the new toolbox
            GlobalValues.extensionClassLoader = new ExtensionClassLoader(forScalaToolboxJarName, (ClassLoader) GlobalValues.scalalabMainFrame.scalalabConsole.scalaInterpreter.scala$tools$nsc$Interpreter$$classLoader());

           int   numClassesOfToolbox=0;
            try {
                GlobalValues.ScalaToolboxesLoader = new JarClassLoader();
                numClassesOfToolbox = GlobalValues.ScalaToolboxesLoader.scanAllToolboxClasses(forScalaToolboxJarName);
            } catch (IOException ex) {
                System.out.println("exception trying to read classes from toolbox "+forScalaToolboxJarName);
                ex.printStackTrace();
            }
           System.out.println("scanned: "+numClassesOfToolbox+",from toolbox: "+forScalaToolboxJarName);
         }
        }  // ScalaSciToolboxesStr != null
*/
        if (GlobalValues.ScalaSciUserPaths!=null) {
           GlobalValues.ScalaSciUserPaths.clear();
           GlobalValues.ScalaSciUserPaths.add(GlobalValues.homeDir);
        }
        else
           GlobalValues.ScalaSciUserPaths = new Vector();

        // extract the user specified path entries
        boolean pathsUpdated = false;  // any paths updated? If so redraw the GUI components
      // if user paths are specified in the "ScalaSciUserPathsProp" update accordingly the path of the Scala interpreter
  
        String ScalaSciUserPathsStr = settings.getProperty("ScalaSciUserPathsProp");
        if (ScalaSciUserPathsStr != null)   {
        StringTokenizer userPathsTok = new StringTokenizer(ScalaSciUserPathsStr, File.pathSeparator);
        while (userPathsTok.hasMoreTokens()) {
            String currentPath = userPathsTok.nextToken().trim();
            if (ScalaSciUserPaths.contains(currentPath)==false)   { // path not already specified
       // append the specified path to the Scala's interpreter path     
           if (GlobalValues.ScalaSciUserPaths.contains(currentPath)==false) {
                GlobalValues.ScalaSciUserPaths.add(currentPath);
           }
              pathsUpdated = true;
              }
           }
        scalaSciCommands.BasicCommands.appendClasspaths(GlobalValues.ScalaSciUserPaths);
        }  // ScalaSciUserPathsStr != null
    

        String notOverlapConsoleOutput = settings.getProperty("notOverlapTheConsoleOutput");
        if (notOverlapConsoleOutput != null)   
         if (notOverlapConsoleOutput.equalsIgnoreCase("false"))
              GlobalValues.notOverlapTheConsoleOutput = false;
         else
             GlobalValues.notOverlapTheConsoleOutput = true;
    
        
        if (scalalabMainFrame != null)  {
           scalalabMainFrame.setSize(sizeX, sizeY);
           scalalabMainFrame.setLocation(locX, locY);
           scalalabMainFrame.setFont(new Font(uiFontName, Font.PLAIN, Double.valueOf(uiFontSize).intValue()));
    if (pathsUpdated)  {  // redraw GUI components
    scalaExec.scalaLab.scalaLab.updateTree();
    scalaExec.scalaLab.scalaLab.outerPane.revalidate();
        }
   }
        

    }
     
    

    // pass properties readed from settings Property String to the scalaLab workspace structures
    public static void passPropertiesFromSettingsToWorkspaceNotPaths(Properties settings)
     {
        String specifiedDir =  settings.getProperty("scalalabWorkingDirProp");         
        if (specifiedDir != null) workingDir = specifiedDir;

        String locXstr = settings.getProperty("xlocProp");
        if (locXstr != null)      locX = Integer.parseInt(locXstr);  // locX specified
        String locYstr = settings.getProperty("ylocProp");
        if (locYstr != null)      locY = Integer.parseInt(locYstr);  // locY specified
        if (GlobalValues.scalalabMainFrame != null)
            GlobalValues.scalalabMainFrame.setLocation(locX, locY);   // update the location of the scalalab's main frame according to the configuration settings

       String sizeXstr = settings.getProperty("widthProp");
        if (sizeXstr != null)      sizeX = Integer.parseInt(sizeXstr);  // sizeX specified
        String sizeYstr = settings.getProperty("heightProp");
        if (sizeYstr != null)      sizeY = Integer.parseInt(sizeYstr);  // sizeY specified
        if (GlobalValues.scalalabMainFrame != null)
            GlobalValues.scalalabMainFrame.setSize(sizeX, sizeY);   // update the size of the scalalab's main frame according to the configuration settings
        
       String sizeConsoleXstr = settings.getProperty("widthConsoleProp");
        if (sizeConsoleXstr != null)      sizeConsoleX = Integer.parseInt(sizeConsoleXstr);  // sizeX Console specified
        String sizeConsoleYstr = settings.getProperty("heightConsoleProp");
        if (sizeConsoleYstr != null)      sizeConsoleY = Integer.parseInt(sizeConsoleYstr);  // sizeY Console specified
        if (GlobalValues.scalalabMainFrame.scalalabConsole != null)
            GlobalValues.consoleOutputWindow.consoleFrame.setSize(sizeConsoleX, sizeConsoleY);
// track the location and size of the output Console  window
        
        String locConsoleXstr = settings.getProperty("xlocConsoleProp");
        if (locConsoleXstr != null)      locConsoleX = Integer.parseInt(locConsoleXstr);  // sizeX Console specified
        String locConsoleYstr = settings.getProperty("ylocConsoleProp");
        if (locConsoleYstr != null)      locConsoleY = Integer.parseInt(locConsoleYstr);  // sizeY Console specified
        if (GlobalValues.scalalabMainFrame.scalalabConsole != null)
            GlobalValues.consoleOutputWindow.consoleFrame.setLocation(locConsoleX, locConsoleY);
        
        String uiFontName = settings.getProperty("uiFontNameProp");
        if (uiFontName==null) uiFontName= GlobalValues.defaultFontName;
        String uiFontSize = settings.getProperty("uiFontSizeProp");
        if (uiFontSize==null) uiFontSize= GlobalValues.defaultFontSize;
                
        String consoleFontName = settings.getProperty("consoleFontNameProp");
        if (consoleFontName==null) consoleFontName= GlobalValues.defaultConsoleFontName;
        String consoleFontSize = settings.getProperty("consoleFontSizeProp");
        if (consoleFontSize==null) consoleFontSize= GlobalValues.defaultConsoleFontSize;
        
        int alpha=255; int red=0; int green=0; int blue=0;
        if (settings.getProperty("alphaProp")!=null)
            alpha = Integer.parseInt(settings.getProperty("alphaProp"));
        if (settings.getProperty("redProp")!=null)
            red = Integer.parseInt(settings.getProperty("redProp"));
        if (settings.getProperty("greenProp")!=null)
           green = Integer.parseInt(settings.getProperty("greenProp"));
        if (settings.getProperty("blueProp")!=null)
            blue = Integer.parseInt(settings.getProperty("blueProp"));
        Color consoleFontColor  = new Color(red, green, blue, alpha);
        
        int isBold = 0, isItalic = 0;
        if (settings.getProperty("isBoldProp")!=null)
          isBold = Integer.parseInt(settings.getProperty("isBoldProp")); 
        if (settings.getProperty("isItalicProp")!=null)
          isItalic = Integer.parseInt(settings.getProperty("isItalicProp"));
        int fontStyle = Font.PLAIN;
        if (isItalic==1) fontStyle = fontStyle | Font.ITALIC;
        if (isBold==1) fontStyle = fontStyle | Font.BOLD;
        
        if (GlobalValues.scalalabMainFrame != null)  {
            Font consoleFont = new Font(consoleFontName, fontStyle, Integer.parseInt(consoleFontSize));
            scalalabMainFrame.scalalabConsole.setFont(consoleFont);
            scalalabMainFrame.scalalabConsole.setForeground(consoleFontColor);
            scalalabMainFrame.setSize(sizeX, sizeY);
            scalalabMainFrame.setLocation(locX, locY);
            scalalabMainFrame.setFont(new Font(uiFontName, Font.PLAIN, Double.valueOf(uiFontSize).intValue()));
       }
        
        if (GlobalValues.notOverlapTheConsoleOutput)
            settings.setProperty("notOverlapTheConsoleOutput", "true");
        else
            settings.setProperty("notOverlapTheConsoleOutput", "false");
        
    }
    
 // updates the paths of targetVector by adding additionalPaths and any subdirectories
public static void updatePathVectors(Vector targetVector,  String additionalPaths, boolean recurse) {
    if (targetVector != null)  {
            StringTokenizer  tokenizer;
             tokenizer = new StringTokenizer(additionalPaths, "\n\t "+File.pathSeparator);
            while (tokenizer.hasMoreTokens())  {  // construct full paths to search for j-files
                String nextToken = tokenizer.nextToken()+File.separatorChar;
                if (recurse == false)
                    targetVector.add(nextToken);
                else
                    scalaLabUtils.appendAllSubDirectories(nextToken, targetVector);
          }
          
    }
}
    

// pass properties from the scalaLab workspace structures to the settings Property String to 
    public static void passPropertiesFromWorkspaceToSettings(Properties settings)
     {
        Settings.StringSetting cp = GlobalValues.scalalabMainFrame.scalalabConsole.scalaSettings.classpath();  // retrieve the current Scala classpath
        String ncp = cp.v();
        if (GlobalValues.ScalaSciClassPath!=null)  
            settings.setProperty("ScalaSciClassPathProp",   ncp);
         // handle any specified additional toolboxes
        if (GlobalValues.ScalaSciToolboxes!=null)   {
            int  toolboxCnt=GlobalValues.ScalaSciToolboxes.size();
            String toolboxSpecString="";
            for (int k=0; k<toolboxCnt; k++)
                toolboxSpecString += GlobalValues.ScalaSciToolboxes.elementAt(k)+File.pathSeparator;
            settings.setProperty("ScalaSciToolboxesProp", toolboxSpecString);
          }
        // handle any specified additional user specified paths
        if (GlobalValues.ScalaSciUserPaths!=null)  {
            int userSpecPathsCnt = GlobalValues.ScalaSciUserPaths.size();
            String userPathsSpecString="";
            for (int k=0; k<userSpecPathsCnt; k++)
                userPathsSpecString += GlobalValues.ScalaSciUserPaths.elementAt(k).toString().trim()+File.pathSeparator;
            settings.setProperty("ScalaSciUserPathsProp", userPathsSpecString); 
          }
         
            
        if (GlobalValues.workingDir!=null)  settings.setProperty("scalalabWorkingDirProp", GlobalValues.workingDir);
           // track the location and size of the main ScalaLab window
        int width = scalalabMainFrame.getSize().width;
        int height = scalalabMainFrame.getSize().height;        
        settings.setProperty("widthProp", String.valueOf(width));
        settings.setProperty("heightProp", String.valueOf(height));
        int xloc = scalalabMainFrame.getLocation().x;
        int yloc = scalalabMainFrame.getLocation().y;
        settings.setProperty("xlocProp", String.valueOf(xloc));
        settings.setProperty("ylocProp", String.valueOf(yloc));
      
// track the location and size of the output Console  window
        int widthConsole = GlobalValues.consoleOutputWindow.consoleFrame.getSize().width;
        int heightConsole = GlobalValues.consoleOutputWindow.consoleFrame.getSize().height;
        settings.setProperty("widthConsoleProp", String.valueOf(widthConsole));
        settings.setProperty("heightConsoleProp", String.valueOf(heightConsole));
        int xlocConsole = GlobalValues.consoleOutputWindow.consoleFrame.getLocation().x;
        int ylocConsole  = GlobalValues.consoleOutputWindow.consoleFrame.getLocation().y;
        settings.setProperty("xlocConsoleProp", String.valueOf(xlocConsole));
        settings.setProperty("ylocConsoleProp", String.valueOf(ylocConsole));
 
        
        settings.setProperty("uiFontNameProp", String.valueOf(scalalabMainFrame.getFont().getName()));
        settings.setProperty("uiFontSizeProp", String.valueOf(scalalabMainFrame.getFont().getSize()));
        settings.setProperty("consoleFontNameProp", String.valueOf(scalalabMainFrame.scalalabConsole.getFont().getName()));
        settings.setProperty("consoleFontSizeProp", String.valueOf(scalalabMainFrame.scalalabConsole.getFont().getSize()));
                
    }
 
        

// clear the properties 
    public static void clearProperties()  {
       settings.setProperty("ScalaSciClassPathProp","");
       settings.setProperty("ScalaSciToolboxesProp", "");   // the property that keeps the user toolboxes
       settings.setProperty("ScalaSciUserPathsProp", "");   // the property that keeps the user specified paths       settings.setProperty("scalalabScriptPath","");
       settings.setProperty("scalalabWorkingDirProp","");
    }

    public static void clearUserPaths() {
       ScalaSciUserPaths = new Vector();
    }
    
    /** @return actual working directory */
    protected String getWorkingDirectory()
    {
        return workingDir;
    }

    /** @param set working directory */
    protected void setWorkingDirectory(String _workingDir)
    {
        workingDir = _workingDir;
    }

    }
